var dao = require('../database/dao'),
  util = require('../helper/util'),
  Log = require('../helper/logger'),
  tagLogger = new Log.TagLogger('COMMON_MODEL');

var genPagination = (exports.genPagination = function(list, page, size, total) {
  return {list, page, size, total};
});

exports.getStarInfoByIds = function(id, callback) {
  let url = urlConf.starUrl + `${id}`;
  adapter.get(url, callback);
};

exports.getProductLineByPage = function(page, size, callback) {
  let [offset, limit] = util.ps2ol(page, size);
  let fromJoinWhere = `FROM ProductLine where status = 0 `;
  let subSql = `select count(1) ${fromJoinWhere}`;
  dao.allNHoistFields(
    `SELECT id,name, (${subSql}) cnt ${fromJoinWhere} ORDER BY id ASC LIMIT ?, ?`,
    [offset, limit],
    ['cnt'],
    (err, rslt) => {
      if (err == null)
        callback(
          null,
          genPagination(rslt.prunedRows, page, size, rslt.cnt || 0),
        );
      else callback(err, null);
    },
  );
};

exports.getProductLineCount = function(callback) {
  dao.getCount('ProductLine', callback);
};

var genUpdateRslt = (exports.genUpdateRslt = function(rslt) {
  return {affectedRows: rslt.affectedRows, changedRows: rslt.changedRows};
});

var genInsertRslt = (exports.genInertRslt = function(rslt) {
  return {insertId: rslt.insertId};
});

var genUpdateBatchRslt = (exports.genUpdateBatchRslt = function(
  rslts,
  fromIdx,
  toIdx,
) {
  fromIdx = fromIdx || 0;
  toIdx = toIdx || rslts.length - 1;
  let affectedRows = 0,
    changedRows = 0;
  for (let i = fromIdx; i <= toIdx; ++i) {
    affectedRows += rslts[i].affectedRows;
    changedRows += rslts[i].changedRows;
  }
  return {affectedRows, changedRows};
});

var genUpdateBatchCallback = (exports.genUpdateBatchCallback = function(
  callback,
  fromIdx,
  toIdx,
) {
  return (err, rslts) => {
    if (err == null) callback(null, genUpdateBatchRslt(rslts, fromIdx, toIdx));
    else callback(err, null);
  };
});

exports.genUpdateCallback = function(callback) {
  return (err, rslt) => {
    if (err == null) callback(null, genUpdateRslt(rslt));
    else callback(err, null);
  };
};

exports.genInsertCallback = function(callback) {
  return (err, rslt) => {
    if (err == null) callback(null, {insertId: rslt.insertId});
    else callback(err, null);
  };
};

exports.genSelectCallback = function(callback, ...rest) {
  let [page, size, total] = rest;
  return (err, rslt) => {
    let data = rslt;
    //tagLogger.debug(`genSelectCallback, data[${JSON.stringify(data)}]`);
    if (err == null) {
      page = page || 1;
      size = size || data.length;
      total = total || data.length;
      callback(null, genPagination(data, page, size, total));
    } else {
      callback(err, null);
    }
  };
};
